package core.task;

import core.db.util.LogUtils;
import core.task.async.bean.Param;
import core.task.async.bean.Result;
import core.task.async.callback.Callback;
import core.task.async.callback.ICallback;
import core.task.async.callback.IWorker;
import core.task.async.executor.Async;
import core.task.async.worker.WorkResult;
import core.task.async.wrapper.WorkerWrapper;

import java.util.concurrent.ExecutionException;

public class Task {
    private final static  int defaultTimeOut = 10*1000;//10秒
    private IWorker iWorker;
    private Param param = new Param();
    private Callback callback;
    public static Task exec(Object obj){
        if(obj==null){
            return null;
        }
        IWorker iWorker = null;
        if(obj instanceof  IWorker){
            iWorker = (IWorker)obj;
        }else if(obj instanceof  Class){
            try {
                Class cls = (Class)obj;
                Object o = cls.newInstance();
                if(o instanceof IWorker){
                    iWorker=(IWorker)o;
                }else{
                    LogUtils.e("您传入执行的class不是IWorker类型!");
                }
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        if(iWorker==null){
            return null;
        }
        return new Task(iWorker);
    }
    public  Task(IWorker iWorker){
        if(iWorker==null){
            return;
        }
        this.iWorker = iWorker;
    }
    public Task addParam(String key, Object value){
        param.add(key,value);
        return this;
    }
    public Task addParam(Object value){
        param.add(value);
        return this;
    }
    public Task callback(Callback callback){
        this.callback = callback;
        return  this;
    }
    public boolean start(){
        if(iWorker==null){
            LogUtils.e("异步线程执行代码块为空！");
            return false;
        }
        try {
            WorkerWrapper<Param, Result> workerWrapper = new WorkerWrapper.Builder<Param, Result>()
                    .worker(iWorker)
                    .param(param)
                    .callback(new ICallback<Param, Result>() {
                        @Override
                        public void result(boolean success, Param param, WorkResult<Result> workResult) {
                            if(callback!=null){
                                callback.result(success,workResult);
                            }
                        }
                    })
                    .build();
            Async.beginWork(defaultTimeOut, workerWrapper);
            return true;
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }

}
